%% Author: wooray
%% Created: 2008-4-16
%% Description: TODO: Add description to map_grider
-module(map_grider).

%%
%% Include files
%%

%%
%% Exported Functions
%%
-export([start/1, init/1]).

%%
%% API Functions
%%
start(ExtPrg) ->
  spawn(?MODULE, init, [ExtPrg]).

init(ExtPrg) ->
  register(map_grider, self()),
  process_flag(trap_exit, true),
  Port = open_port({spawn, ExtPrg}, [{packet, 2}, binary]),
  loop(Port).


%%
%% Local Functions
%%
loop(Port) ->
	receive
    	{call, Caller, Msg} ->
      	Port ! {self(), {command, term_to_binary(Msg)}},
      	receive
          	{Port, {data, Data}} ->
          	Caller ! {map_grider, binary_to_term(Data)}
      	end,
      	loop(Port);
	stop ->
        Port ! {self(), close},
        receive
        	{Port, closed} ->
            	exit(normal)
       	end;
	{'EXIT', Port, _Reason} ->
    	exit(port_terminated)
 end.
